package com.code2roc.fastboot.system.codegen.bizlogic;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.code2roc.fastboot.framework.util.*;
import com.code2roc.fastboot.system.codegen.model.DataBaseColumnInfo;
import com.code2roc.fastboot.system.codegen.model.DataBaseTableInfo;
import com.code2roc.fastboot.system.codegen.model.SystemColumnDO;
import com.code2roc.fastboot.system.codegen.model.SystemTableDO;
import com.code2roc.fastboot.system.codegen.service.ISystemColumnService;
import com.code2roc.fastboot.system.codegen.service.ISystemTableService;
import com.code2roc.fastboot.model.BaseBootLogic;
import com.code2roc.fastboot.framework.database.CommonDTO;
import com.code2roc.fastboot.framework.datasource.DataSourceContextHolder;
import com.code2roc.fastboot.framework.datasource.DynamicDataSource;
import com.code2roc.fastboot.util.BootUtil;
import freemarker.template.Template;
import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@Component
public class CodeGenLogic extends BaseBootLogic {
    @Autowired
    private DynamicDataSource dynamicDataSource;
    @Autowired
    private CommonDTO commonDTO;
    @Autowired
    private ISystemTableService tableService;
    @Autowired
    private ISystemColumnService columnService;
    @Autowired
    private FreeMarkerConfigurer configurer;

    public String getSchemaName() {
        String dataSourceID = DataSourceContextHolder.getDataSource();
        if (StringUtil.isEmpty(dataSourceID)) {
            dataSourceID = "master";
        }
        DruidDataSource dataSource = dynamicDataSource.getDataSource(dataSourceID);
        return dataSource.getUrl().split("//")[1].split("/")[1].split("\\?")[0];
    }

    public DataBaseTableInfo getDataBaseTableInfo(String tableName) {
        String sql = "table_schema = #{table_schema} and table_name = #{table_name}";
        HashMap paramMap = new HashMap();
        paramMap.put("table_schema", getSchemaName());
        paramMap.put("table_name", tableName);
        return commonDTO.selectOne(DataBaseTableInfo.class, "information_schema.tables", "table_name as table_name,create_time as create_time,update_time as update_time,table_comment as table_comment", sql, paramMap);
    }

    public List<DataBaseColumnInfo> getDataBaseColumnInfo(String table_name) {
        HashMap paramMap = new HashMap();
        String selectTableName = "information_schema.columns";
        String selectColumnName = "table_name AS table_name,column_name AS column_name,data_type AS data_type,numeric_precision AS numeric_precision,numeric_scale AS numeric_scale,character_maximum_length AS character_maximum_length,column_comment as column_comment";
        String sql = "table_schema = #{table_schema} and table_name = #{table_name}";
        paramMap.put("table_schema", getSchemaName());
        paramMap.put("table_name", table_name);
        List<LinkedHashMap<String, Object>> columnList = commonDTO.selectList(selectTableName, selectColumnName, sql, "", paramMap);
        List<DataBaseColumnInfo> rows = new ArrayList<>();
        for (LinkedHashMap<String, Object> itemMap : columnList) {
            String column_name = ConvertOp.convert2String(itemMap.get("column_name"));
            String data_type = ConvertOp.convert2String(itemMap.get("data_type"));
            String numeric_precision = ConvertOp.convert2String(itemMap.get("numeric_precision"));
            String numeric_scale = ConvertOp.convert2String(itemMap.get("numeric_scale"));
            String character_maximum_length = ConvertOp.convert2String(itemMap.get("character_maximum_length"));
            String column_comment = ConvertOp.convert2String(itemMap.get("column_comment"));

            DataBaseColumnInfo dataBaseColumnInfo = new DataBaseColumnInfo();
            dataBaseColumnInfo.setTable_name(table_name);
            dataBaseColumnInfo.setColumn_name(column_name);
            dataBaseColumnInfo.setData_type(data_type);
            dataBaseColumnInfo.setNumeric_precision(numeric_precision);
            dataBaseColumnInfo.setNumeric_scale(numeric_scale);
            dataBaseColumnInfo.setCharacter_maximum_length(character_maximum_length);
            dataBaseColumnInfo.setColumn_comment(column_comment);
            rows.add(dataBaseColumnInfo);
        }
        return rows;
    }

    public String getColumnType(DataBaseColumnInfo columnInfo) {
        String columnType = "";
        switch (columnInfo.getData_type()) {
            case "longtext":
                columnType = columnInfo.getData_type();
                break;
            case "datetime":
                columnType = columnInfo.getData_type();
                break;
            case "date":
                columnType = columnInfo.getData_type();
                break;
            case "int":
                columnType = columnInfo.getData_type();
                break;
            case "varchar":
                columnType = "varchar(" + columnInfo.getCharacter_maximum_length() + ")";
                break;
            case "decimal":
                columnType = "decimal(" + columnInfo.getNumeric_precision() + "," + columnInfo.getNumeric_scale() + ")";
                break;
        }
        return columnType;
    }

    public String getControlType(DataBaseColumnInfo columnInfo) {
        String control_type = "";
        switch (columnInfo.getData_type()) {
            case "longtext":
                control_type = "textarea";
                break;
            case "datetime":
                control_type = "date";
                break;
            case "date":
                control_type = "date";
                break;
            case "int":
                control_type = "intinput";
                break;
            case "varchar":
                control_type = "input";
                break;
            case "decimal":
                control_type = "numberinput";
                break;
        }
        return control_type;
    }

    public void imortTable(DataBaseTableInfo tableInfo) {

        SystemTableDO tableDO = new SystemTableDO();
        tableDO.setTable_name(tableInfo.getTable_name());
        tableDO.setTable_description(tableInfo.getTable_comment());
        tableDO.setGmt_create(tableInfo.getCreate_time());
        tableDO.setGmt_modified(tableInfo.getUpdate_time());
        tableService.insert(tableDO);
        List<DataBaseColumnInfo> columnInfoList = getDataBaseColumnInfo(tableInfo.getTable_name());
        for (DataBaseColumnInfo columnInfo : columnInfoList) {
            importColumn(columnInfo, tableDO.getRow_id());
        }
    }

    public void importColumn(DataBaseColumnInfo columnInfo, String row_id) {
        List<String> baseFieldList = new ArrayList<>();
        baseFieldList.add("id");
        baseFieldList.add("row_id");
        baseFieldList.add("sort_num");
        baseFieldList.add("gmt_create");
        baseFieldList.add("gmt_modified");
        if (!baseFieldList.contains(columnInfo.getColumn_name())) {
            SystemColumnDO columnDO = new SystemColumnDO();
            columnDO.setColumn_name(columnInfo.getColumn_name());
            columnDO.setColumn_description(columnInfo.getColumn_comment());
            columnDO.setColumn_type(getColumnType(columnInfo));
            columnDO.setTable_id(row_id);
            columnService.insert(columnDO);
        }
    }

    public void syncTable(String tableName) {
        DataBaseTableInfo tableInfo = getDataBaseTableInfo(tableName);
        SystemTableDO tableDO = tableService.selectOneByField("table_name", tableName);
        tableDO.setTable_name(tableInfo.getTable_name());
        tableDO.setTable_description(tableInfo.getTable_comment());
        tableDO.setGmt_create(tableInfo.getCreate_time());
        tableDO.setGmt_modified(tableInfo.getUpdate_time());
        tableService.update(tableDO);
        List<DataBaseColumnInfo> columnInfoList = getDataBaseColumnInfo(tableName);
        List<SystemColumnDO> columnDOList = columnService.selectListByField("table_id", tableDO.getRow_id());

        //代码设置有，数据库没有，删除
        for (SystemColumnDO columnDO : columnDOList) {
            List<DataBaseColumnInfo> filterList = columnInfoList.stream().filter(a -> a.getColumn_name().equals(columnDO.getColumn_name())).collect(Collectors.toList());
            if (filterList.size() == 0) {
                columnService.delete(columnDO.getRow_id());
            }
        }

        //数据库有，代码设置没有，新增
        //数据库有，代码设置有，更新
        for (DataBaseColumnInfo columnInfo : columnInfoList) {
            List<SystemColumnDO> filterList = columnDOList.stream().filter(a -> a.getColumn_name().equals(columnInfo.getColumn_name())).collect(Collectors.toList());
            if (filterList.size() == 0) {
                //新增
                importColumn(columnInfo, tableDO.getRow_id());
            } else {
                //更新
                SystemColumnDO columnDO = filterList.get(0);
                columnDO.setColumn_name(columnInfo.getColumn_name());
                columnDO.setColumn_description(columnInfo.getColumn_comment());
                columnDO.setColumn_type(getColumnType(columnInfo));
                columnService.update(columnDO);
            }
        }

    }

    public byte[] createCode(String codeFolder, List<String> tableNameList) {
        codeFolder = codeFolder + "/";
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        try {
            String fileName = "";
            for (String tableName : tableNameList) {
                //生成model
                fileName = createModelTemplate(codeFolder, tableName);
                zip.putNextEntry(new ZipEntry(fileName.replace("tempfiles/codegen/", "")));
                zip.write(FileUtil.getBytes(fileName));
                zip.closeEntry();
                //生成dao
                fileName = createDaoTemplate(codeFolder, tableName);
                zip.putNextEntry(new ZipEntry(fileName.replace("tempfiles/codegen/", "")));
                zip.write(FileUtil.getBytes(fileName));
                zip.closeEntry();
                //生成Service
                fileName = createServiceTemplate(codeFolder, tableName);
                zip.putNextEntry(new ZipEntry(fileName.replace("tempfiles/codegen/", "")));
                zip.write(FileUtil.getBytes(fileName));
                zip.closeEntry();
                //生成ServiceImpl
                fileName = createServiceImplTemplate(codeFolder, tableName);
                zip.putNextEntry(new ZipEntry(fileName.replace("tempfiles/codegen/", "")));
                zip.write(FileUtil.getBytes(fileName));
                zip.closeEntry();
                //生成Controller
                fileName = createControllerTemplate(codeFolder, tableName);
                zip.putNextEntry(new ZipEntry(fileName.replace("tempfiles/codegen/", "")));
                zip.write(FileUtil.getBytes(fileName));
                zip.closeEntry();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }

    private String createModelTemplate(String codeFolder, String tableName) {
        String fileName = "";
        try {
            SystemTableDO tableDO = tableService.selectOneByField("table_name", tableName);
            List<SystemColumnDO> entityList = columnService.selectListByField("table_id", tableDO.getRow_id());
            String packageName = tableDO.getPackage_name();
            codeFolder += StringUtil.getConverPath(packageName + ".model");
            FileUtil.initfloderPath(codeFolder);
            String className = getModelName(tableName);
            String suffix = className + ".java";
            fileName = codeFolder + suffix;
            File codeFile = new File(fileName);
            if (!codeFile.exists()) {
                codeFile.createNewFile();
            }

            JSONArray columnList = new JSONArray();
            for (SystemColumnDO entity : entityList) {
                JSONObject column = new JSONObject();
                column.put("columnName", entity.getColumn_name());
                String columnType = "";
                if (entity.getColumn_type().startsWith("varchar") || entity.getColumn_type().startsWith("longtext")) {
                    columnType = "text";
                } else if (entity.getColumn_type().startsWith("int")) {
                    columnType = "int";
                } else if (entity.getColumn_type().startsWith("decimal")) {
                    columnType = "numeric";
                } else if (entity.getColumn_type().startsWith("date")) {
                    columnType = "date";
                }
                column.put("columnType", columnType);
                columnList.add(column);
            }

            Map<String, Object> templaetParam = new HashMap<String, Object>();
            templaetParam.put("tableName", tableName);
            templaetParam.put("packageName", packageName);
            templaetParam.put("className", className);
            templaetParam.put("columnList", columnList);
            createFileByTemplate("Model.ftl", codeFile, templaetParam, suffix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    private String createDaoTemplate(String codeFolder, String tableName) {
        String fileName = "";
        try {
            SystemTableDO tableDO = tableService.selectOneByField("table_name", tableName);
            String packageName = tableDO.getPackage_name();
            codeFolder += StringUtil.getConverPath(packageName + ".dao");
            FileUtil.initfloderPath(codeFolder);
            String className = getDaoName(tableName);
            String suffix = className + ".java";
            fileName = codeFolder + suffix;
            File codeFile = new File(fileName);
            if (!codeFile.exists()) {
                codeFile.createNewFile();
            }

            Map<String, Object> templaetParam = new HashMap<String, Object>();
            templaetParam.put("packageName", packageName);
            templaetParam.put("className", className);
            templaetParam.put("classModelName", getModelName(tableName));
            createFileByTemplate("Dao.ftl", codeFile, templaetParam, suffix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    private String createServiceTemplate(String codeFolder, String tableName) {
        String fileName = "";
        try {
            SystemTableDO tableDO = tableService.selectOneByField("table_name", tableName);
            String packageName = tableDO.getPackage_name();
            codeFolder += StringUtil.getConverPath(packageName + ".service");
            FileUtil.initfloderPath(codeFolder);
            String className = getClassName(tableName);
            String suffix = "I" + className + "Service" + ".java";
            fileName = codeFolder + suffix;
            File codeFile = new File(fileName);
            if (!codeFile.exists()) {
                codeFile.createNewFile();
            }

            Map<String, Object> templaetParam = new HashMap<String, Object>();
            templaetParam.put("packageName", packageName);
            templaetParam.put("className", className);
            templaetParam.put("classModelName", getModelName(tableName));
            createFileByTemplate("Service.ftl", codeFile, templaetParam, suffix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    private String createServiceImplTemplate(String codeFolder, String tableName) {
        String fileName = "";
        try {
            SystemTableDO tableDO = tableService.selectOneByField("table_name", tableName);
            String packageName = tableDO.getPackage_name();
            codeFolder += StringUtil.getConverPath(packageName + ".service.impl");
            FileUtil.initfloderPath(codeFolder);
            String className = getClassName(tableName);
            String suffix = className + "ServiceImpl" + ".java";
            fileName = codeFolder + suffix;
            File codeFile = new File(fileName);
            if (!codeFile.exists()) {
                codeFile.createNewFile();
            }

            Map<String, Object> templaetParam = new HashMap<String, Object>();
            templaetParam.put("packageName", packageName);
            templaetParam.put("className", className);
            templaetParam.put("classModelName", getModelName(tableName));
            createFileByTemplate("ServiceImpl.ftl", codeFile, templaetParam, suffix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    private String createControllerTemplate(String codeFolder, String tableName) {
        String fileName = "";
        try {
            SystemTableDO tableDO = tableService.selectOneByField("table_name", tableName);
            String packageName = tableDO.getPackage_name();
            codeFolder += StringUtil.getConverPath(packageName + ".controller");
            FileUtil.initfloderPath(codeFolder);
            String className = getClassName(tableName);
            String suffix = className + "Controller" + ".java";
            fileName = codeFolder + suffix;
            File codeFile = new File(fileName);
            if (!codeFile.exists()) {
                codeFile.createNewFile();
            }

            Map<String, Object> templaetParam = new HashMap<String, Object>();
            templaetParam.put("packageName", packageName);
            templaetParam.put("className", className);
            templaetParam.put("classModelName", getModelName(tableName));
            templaetParam.put("rounterName", tableDO.getRoute_path());
            createFileByTemplate("Controller.ftl", codeFile, templaetParam, suffix);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fileName;
    }

    private void createFileByTemplate(String templateName, File beanFile, Map<String, Object> templateParams, String fileTypeName) throws Exception {
        Template template = configurer.getConfiguration().getTemplate(templateName);
        FileOutputStream fos = new FileOutputStream(beanFile);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
        template.process(templateParams, out);
        fos.close();
    }

    private String getClassName(String tableName) {
        String[] tableNameList = tableName.split("_");
        String className = "";
        for (String item : tableNameList) {
            className += StringUtils.capitalise(item);
        }
        return className;
    }

    private String getModelName(String tableName) {
        return getClassName(tableName) + "DO";
    }

    private String getDaoName(String tableName) {
        return getClassName(tableName) + "Dao";
    }

    public String exportData(List<String> tableNameList) {
        String fileid = "";
        try {
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Calendar calendar = Calendar.getInstance();
            String dateName = df.format(calendar.getTime());
            fileid = "StrcutExport_" + dateName + CommonUtil.getNewGuid();
            String filename = fileid + ".xml";
            String filefullpath = "tempfiles/export/" + filename;
            FileUtil.initfloderPath("tempfiles/export/");
            Document doc = DocumentHelper.createDocument();
            Element root = doc.addElement("strcutfile");
            Element filetype = root.addElement("filetype");
            filetype.setText("table");

            Element tablelist = root.addElement("tablelist");
            for (String tableName : tableNameList) {
                SystemTableDO tableDO = tableService.selectOneByField("table_name", tableName);
                Element table = tablelist.addElement("table");
                for (Field field : tableDO.getClass().getDeclaredFields()) {
                    if (!Modifier.isStatic(field.getModifiers())) {
                        field.setAccessible(true);
                        Element tablefield = table.addElement(field.getName());
                        tablefield.setText(String.valueOf(field.get(tableDO)));
                    }
                }
                Element columnlist = table.addElement("columnlist");
                List<SystemColumnDO> columnDOList = columnService.selectList("*", "table_id='" + tableDO.getRow_id() + "'", "id", new HashMap<>());
                for (SystemColumnDO columnDO : columnDOList) {
                    Element column = columnlist.addElement("column");
                    for (Field field : columnDO.getClass().getDeclaredFields()) {
                        if (!Modifier.isStatic(field.getModifiers())) {
                            field.setAccessible(true);
                            Element columnfield = column.addElement(field.getName());
                            columnfield.setText(String.valueOf(field.get(columnDO)));
                        }
                    }
                }
            }
            OutputFormat format = OutputFormat.createPrettyPrint();
            format.setEncoding("utf-8");
            FileOutputStream out;
            out = new FileOutputStream(filefullpath);
            XMLWriter writer = new XMLWriter(out, format);
            writer.write(doc);
            writer.close();

            StringBuilder builder = new StringBuilder();
            builder.append("导出物理结构信息成功！" + CommonUtil.getNewLine());
            LogUtil.writeLog("strcut", "log", builder.toString());
        } catch (Exception e) {
            e.printStackTrace();
            StringBuilder builder = new StringBuilder();
            builder.append("导出物理结构信息失败！" + CommonUtil.getNewLine());
            builder.append("失败异常信息:" + CommonUtil.getNewLine());
            builder.append(e.getMessage() + CommonUtil.getNewLine());
            builder.append("失败堆栈信息:" + CommonUtil.getNewLine());
            builder.append(e.getStackTrace());
            LogUtil.writeLog("strcut", "log", builder.toString());
        }
        return fileid;
    }

    public String importData(InputStream stream) {
        String errormsg = "";
        Exception exception = null;
        try {
            //解析xml
            SAXReader reader = new SAXReader();
            Document document = reader.read(stream);
            Element root = document.getRootElement();
            Element filetype = root.element("filetype");
            List<Element> tablelist = root.element("tablelist").elements("table");
            List<SystemTableDO> tableDOList = new ArrayList<>();
            List<SystemColumnDO> columnDOList = new ArrayList<>();
            if (filetype != null && filetype.getText().equals("table")) {
                for (Element table : tablelist) {
                    SystemTableDO tableDO = new SystemTableDO();
                    for (Field field : tableDO.getClass().getDeclaredFields()) {
                        if (!Modifier.isStatic(field.getModifiers())) {
                            field.setAccessible(true);
                            Element filednode = table.element(field.getName());
                            field.set(tableDO, BootUtil.convetXmlContent2FieldContent(filednode.getText(), field.getType()));
                        }
                    }
                    tableDOList.add(tableDO);

                    List<Element> columnlist = table.element("columnlist").elements("column");
                    for (Element column : columnlist) {
                        SystemColumnDO columnDO = new SystemColumnDO();
                        for (Field field : columnDO.getClass().getDeclaredFields()) {
                            if (!Modifier.isStatic(field.getModifiers())) {
                                field.setAccessible(true);
                                Element filednode = column.element(field.getName());
                                field.set(columnDO, BootUtil.convetXmlContent2FieldContent(filednode.getText(), field.getType()));
                            }
                        }
                        columnDOList.add(columnDO);
                    }
                }
                if (tableDOList.size() > 0) {
                    List<String> tableNameList = tableDOList.stream().map(a -> a.getTable_name()).collect(Collectors.toList());
                    List<SystemTableDO> existTableList = tableService.selectList("*", "table_name in (" + StringUtil.dealWithStringListByStream(tableNameList) + ")", "", new HashMap<>());
                    List<String> tableIDList = new ArrayList<>();
                    if (existTableList.size() > 0) {
                        tableIDList = existTableList.stream().map(a -> a.getRow_id()).collect(Collectors.toList());
                    }
                    String deleteTableSQL = "delete from system_table where table_name in (" + StringUtil.dealWithStringListByStream(tableNameList) + ")";
                    commonDTO.executeSQL(deleteTableSQL, new HashMap<>());
                    String deleteColumnSQL = "delete from system_column where table_id in (" + StringUtil.dealWithStringListByStream(tableIDList) + ")";
                    commonDTO.executeSQL(deleteColumnSQL, new HashMap<>());

                    //创建结构
                    for (SystemTableDO table : tableDOList) {
                        DataBaseTableInfo dataBaseTableInfo = getDataBaseTableInfo(table.getTable_name());
                        if (dataBaseTableInfo == null) {
                            //创建表
                            String createTableSQL = "CREATE TABLE `" + table.getTable_name() + "` (\n" +
                                    "  `id` int(11) NOT NULL AUTO_INCREMENT,\n" +
                                    "  `row_id` varchar(50) DEFAULT NULL,\n" +
                                    "  `sort_num` int(11) DEFAULT NULL,\n" +
                                    "  `gmt_create` datetime DEFAULT NULL,\n" +
                                    "  `gmt_modified` datetime DEFAULT NULL,\n" +
                                    "  PRIMARY KEY (`id`)\n" +
                                    ") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='"+table.getTable_description()+"';";
                            commonDTO.executeSQL(createTableSQL, new HashMap<>());
                        }
                        List<SystemColumnDO> columnList = columnDOList.stream().filter(a -> a.getTable_id().equals(table.getRow_id())).collect(Collectors.toList());
                        List<DataBaseColumnInfo> dataBaseColumnInfoList = getDataBaseColumnInfo(table.getTable_name());
                        for (SystemColumnDO column : columnList) {
                            boolean columnExist = dataBaseColumnInfoList.stream().filter(a -> a.getColumn_name().equals(column.getColumn_name())).count() > 0;
                            if (!columnExist) {
                                //创建列
                                String createColumnSQL = "ALTER TABLE `" + table.getTable_name() + "` ADD COLUMN `" + column.getColumn_name() + "` " + column.getColumn_type() + " DEFAULT NULL  COMMENT '" + column.getColumn_description() + "'";
                                commonDTO.executeSQL(createColumnSQL, new HashMap<>());
                            }
                        }
                    }
                    //插入数据
                    tableService.batchInsert(tableDOList);
                    columnService.batchInsert(columnDOList);
                }
            } else {
                errormsg = "导入文件不是物理结构文件！";
            }
        } catch (Exception e) {
            exception = e;
            errormsg = "导入失败";
            e.printStackTrace();
        } finally {
            StringBuilder builder = new StringBuilder();
            if (StringUtil.isEmpty(errormsg)) {
                builder.append("导入物理结构成功！" + CommonUtil.getNewLine());
            } else {
                builder.append("导入物理结构失败！" + CommonUtil.getNewLine());
            }
            if (!StringUtil.isEmpty(errormsg)) {
                if (errormsg.equals("导入失败")) {
                    builder.append("失败异常信息:" + CommonUtil.getNewLine());
                    builder.append(exception.getMessage() + CommonUtil.getNewLine());
                    builder.append("失败堆栈信息:" + CommonUtil.getNewLine());
                    builder.append(exception.getStackTrace());
                } else {
                    builder.append("导入失败信息:" + errormsg + CommonUtil.getNewLine());
                }
            }
            LogUtil.writeLog("struct", "log", builder.toString());
        }
        return errormsg;
    }
}
